<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/30
 * Time: 16:10
 */
namespace app\team\controller;

use app\admin\model\Appraise as App;
use app\team\model\Order as OrderModel;
use phpexcel\PHPExcel;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use app\common\model\LogOrderModel as lo;
use app\common\model\OrderCancelModel as ocm;
class Order extends Common
{
    /*
     * 管理员列表
     */
    public function order()
    {
        if (Request::instance()->isAjax()) {
            $pagedata = Request::instance()->get();
            $pagesize = $pagedata['limit'];
            $page     = (int) $pagedata['page'];
            if ($page == 1) {
                $startrow = 0;
            } else {
                $startrow = ($page - 1) * $pagesize;
            }
            $where = [];
            if (isset($pagedata['order_sn']) && $pagedata['order_sn'] != '') {

                $where['g.order_sn'] = array('like', '%' . $pagedata['order_sn'] . '%');

            }
            if (isset($pagedata['gtour_title']) && $pagedata['gtour_title'] != '') {

                $where['gtour_title'] = array('like', '%' . $pagedata['gtour_title'] . '%');

            }
            if (isset($pagedata['order_status']) && $pagedata['order_status'] != '') {

                $where['order_status'] = array('like', '%' . $pagedata['order_status'] . '%');

            } else {
                $where['order_status'] = ['in', [3, 4]];
            }
            if (isset($pagedata['search_start_time']) && $pagedata['search_start_time'] != '') {
                $datestart              = strtotime(substr($pagedata['search_start_time'], 0, 10));
                $dateend                = strtotime(substr($pagedata['search_start_time'], 13, 10));
                $where['g.create_time'] = array('between time', array($datestart, $dateend));
            }
            $id   = Session::get('team')['team_id'];
            $data = OrderModel::getOrderList($id, $where, $startrow, $pagesize);
            Session::set('data', $data);
            $count = OrderModel::getOrderCount($id, $where);
            return json(array('code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $data));
        } else {
            $where['order_status'] = ['in', [3, 4]];
            $res = Db::name('gtour_order')
                ->field('order_sn')
                ->where('team_id',Session::get('team')['team_id'])
                ->where('is_del',0)
                ->where($where)
                ->select();
            $this->assign('order',$res);
            return view();
        }
    }

    /*
     * 核销页面
     */
    public function cancel()
    {
        if (Request::instance()->isAjax()) {
            $pagedata = Request::instance()->get();
            $pagesize = $pagedata['limit'];
            $page     = (int) $pagedata['page'];
            if ($page == 1) {
                $startrow = 0;
            } else {
                $startrow = ($page - 1) * $pagesize;
            }
            $where['order_status'] = array('eq', 1);
            if (isset($pagedata['cancel_code']) && $pagedata['cancel_code'] != '') {
                $where['cancel_code'] = ['eq', "team_cancle_code_" . $pagedata['cancel_code']];

            }
            $id   = Session::get('team')['team_id'];
            $data = OrderModel::getOrderList($id, $where, $startrow, $pagesize);
            Session::set('data', $data);
            $count = OrderModel::getOrderCount($id, $where);
            return json(array('code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $data));
        } else {
            return view();
        }
    }

    /*
     * 确认核销
     */
    public function cancelPass()
    {
        if (Request::instance()->isAjax()) {
            $postData = input('param.');
            //先查询一下订单是否已经被核销了
            $order = Db::name('gtour_order')
            ->alias('a')->field('a.*,t.no_settled_order_fee,t.no_settled_order_num')
            ->join('team t','a.team_id=t.team_id','left')->where('order_id', $postData['id'])->find();
            if ($order) {
                Db::startTrans();

                try {
                    if($order['order_status']==7){
                        return 7;
                    }
                    if ($order['order_status'] != 1) {
                        return 2;
                    }
                    //处理今天的时间戳
                    $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
                    $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

                    //判断是否是今天的
                    if($order['gtour_start']<$beginToday || $order['gtour_start']>$endToday){
                        return 4;
                    }
                    //计算订单佣金
                    $commissionFee = 0;
                    if ($order['commission_rate'] > 0) {
                        $commissionFee = $order['total_price'] * $order['gtour_number'] * $order['commission_rate'] / 1000;

                    }

                    // 核销该订单信息
                    $OrderCancel = new ocm();
                    $OrderCancel->orderCancel(Session::get('t_admin_id'), 3, $order['order_id'], $order['order_sn'], $order['order_price']);
                    //创建订单日志
                    $logOrder = new lo();
                    $logOrder->addLogOrder($order['order_id'], 3, Session::get('t_admin_id'), 3, "核销成功");
                    //修改商家未计算订单数和未结算的订单佣金
                    Db::name("team")
                        ->where("team_id", Session::get('team')['team_id'])
                        ->setInc("no_settled_order_num", 1);

                    Db::name("team")
                        ->where("team_id", Session::get('team')['team_id'])
                        ->setDec('no_settled_order_fee',$commissionFee);

                    $data = [
                        'order_status'   => 3,
                        'commission_fee' => $commissionFee,
                    ];
                    //修改订单状态
                    $res = Db::name('gtour_order')->where('order_id', $postData['id'])->update($data);
                    if ($res) {

                        Db::commit();
                        return 0;
                    } else {
                        Db::rollback();
                        return 1;
                    }

                } catch (\Exection $e) {
                    Db::rollback();

                    return 1;
                }

            }
//            //修改订单状态
//            $res = Db::name('gtour_order')->where('order_id', $postData['id'])->setField('order_status', 3);
//            if ($res) {
//                //插入到核销表
//                $data = [
//                    'cancel_id'   => Session::get('t_admin_id'),
//                    'order_sn'    => $postData['sn'],
//                    'order_id'    => $postData['id'],
//                    'create_time' => date('Y-m-d H:i:s'),
//                    'type'        => 3,
//                    'money'       => $postData['money'],
//                ];
//                $res = Db::name('order_cancel')->insertGetId($data);
//                if ($res) {
//                    return 0;
//                } else {
//                    return 1;
//                }
//            } else {
//                return 1;
//            }
        }
    }

    public function cancel_order()
    {
        if (Request::instance()->isAjax()) {
            $pagedata = Request::instance()->get();
            $pagesize = $pagedata['limit'];
            $page     = (int) $pagedata['page'];
            if ($page == 1) {
                $startrow = 0;
            } else {
                $startrow = ($page - 1) * $pagesize;
            }
            $where['type'] = array('eq', 3);
            if (isset($pagedata['order_sn']) && $pagedata['order_sn'] != '') {
                $where['order_sn'] = array('like', '%' . $pagedata['order_sn'] . '%');

            }
            if (isset($pagedata['admin_rename']) && $pagedata['admin_rename'] != '') {

                $where['admin_rename'] = array('like', '%' . $pagedata['admin_rename'] . '%');

            }
            if (isset($pagedata['search_start_time']) && $pagedata['search_start_time'] != '') {
                $datestart            = strtotime(substr($pagedata['search_start_time'], 0, 10));
                $dateend              = strtotime(substr($pagedata['search_start_time'], 13, 10));
                $where['create_time'] = array('between time', array($datestart, $dateend));
            }
            $id   = Session::get('team')['team_id'];
            $data = Db::name('order_cancel')->alias('a')
                ->field('a.*,t.admin_rename')
                ->join('team_admin t', 'a.cancel_id = t.t_admin_id', 'LEFT')
                ->where('t.team_id', $id)
                ->where($where)
                ->order('a.id','desc')
                ->limit($startrow, $pagesize)
                ->select();
            // $data = OrderModel::getOrderList($id,$where,$startrow,$pagesize);
            Session::set('data', $data);
            $count = Db::name('order_cancel')->alias('a')
                ->field('a.*,t.admin_rename')
                ->join('team_admin t', 'a.cancel_id = t.t_admin_id', 'LEFT')
                ->where('t.team_id', $id)
                ->where($where)
                ->count();
            return json(array('code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $data));
        } else {
            //查询是这个商户下的所有姓名
            $res = Db::name('team_admin')
                ->field('admin_rename')
                ->where('team_id', Session::get('team')['team_id'])
                ->where('is_use', 1)
                ->where('is_del', 0)
                ->select();
            $order = Db::name('order_cancel')->alias('a')
                ->field('order_sn')
                ->join('team_admin t', 'a.cancel_id = t.t_admin_id', 'LEFT')
                ->where('t.team_id', Session::get('team')['team_id'])
                ->where('type','3')
                ->select();

            $this->assign('order',$order);
            $this->assign('res', $res);
            return view();
        }
    }
    /**
    查看评价
     */
    public function getAppInfo()
    {
        if (Request::instance()->isAjax()) {
            $post              = Request::instance()->post();
            $where['order_id'] = ['eq', $post['order_id']];
            $where['type']     = ['eq', $post['type']];
            $app               = new App();
            $res               = $app->getAppInfo($where);
            if (!empty($res)) {
                $res['create_time'] = date('Y-m-d H:i:s', $res['create_time']);
                if ($res['eval_status'] == 1) {
                    $res['eval_status'] = "好评";
                } else {
                    $res['eval_status'] = "差评";
                }

                $res['images'] = explode(',', $res['images']);
            }

            if ($res) {
                return json(array('code' => 1, 'msg' => '返回成功', 'data' => $res));
                // ajax_return(1,'返回成功',$res);
            } else {
                return json(array('code' => 0, 'msg' => '暂无评价', 'data' => $res));
            }
        }
    }

    /*
     * 导出excel
     */
    public function excel()
    {
        $array = [
            ['order_id' => '订单ID', 'order_sn' => '订单编号', 'linkman' => '取票人姓名', 'tel' => '取票人电话', 'order_price' => '价格'
                , 'order_status' => '订单状态', 'pay_type' => '支付方式', 'create_time' => '订单时间', 'nickname' => '购买人', 'gtour_title' => '购买商品名称'],
        ];

        $data = Session::get('data');

        foreach ($data as $k => $v) {
            if ($v['order_status'] == '1') {
                $data[$k]['order_status'] = '未出行';
            }
            if ($v['order_status'] == '3') {
                $data[$k]['order_status'] = '待评价';
            }
            if ($v['order_status'] == '4') {
                $data[$k]['order_status'] = '已完成';
            }
            if ($v['pay_type'] == '1') {
                $data[$k]['pay_type'] = '支付宝';
            }
            if ($v['pay_type'] == '2') {
                $data[$k]['pay_type'] = '微信';
            }
        }
        $data = array_merge($array, $data);

        // 下载文件名,默认当前时间'YmdHis'
        $filename = '';

        // 设置列宽,一般为strlen() + 1
        // 常用列宽
        // 手机号:12
        // 日期:11
        // 日期时间:20
        $widtharray = ['A' => 10, 'B' => 10, 'C' => 10, 'D' => 10];

// 其他设置
        // eg:合并单元格,合并的单元格其他位置需填充''
        $settings = [
            //'mergeCells' => ['B2:B4', 'D2:D4'],
        ];

        PHPExcel::download($data, $filename, $widtharray, $settings);
    }
}
